package net.chasing.androidbaseconfig.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;

import androidx.recyclerview.widget.RecyclerView;

import net.chasing.androidbaseconfig.R;

public class HeightLimitRecyclerView extends RecyclerView {

    private static final String TAG = HeightLimitRecyclerView.class.getSimpleName();

    private int mMaxHeight;

    public HeightLimitRecyclerView(Context context) {
        this(context, null, 0);
    }

    public HeightLimitRecyclerView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public HeightLimitRecyclerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        TypedArray arr = context.obtainStyledAttributes(attrs, R.styleable.HeightLimitRecyclerView);
        mMaxHeight =
                arr.getDimensionPixelOffset(R.styleable.HeightLimitRecyclerView_limit_height, -1);
        arr.recycle();
    }

    public void setMaxHeight(int mMaxHeight) {
        this.mMaxHeight = mMaxHeight;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int temHeightSpec = heightMeasureSpec;
        int measuredHeight = getMeasuredHeight();
        if (measuredHeight == 0) {
            /*
            一开始View是GONE的，刚进行VISIBLE的时候，高度可能返回0，导致布局先加载显示成正常的高度
            所以这里进行过滤，如果还没测量到高度，则进行INVISIBLE不显示，待加载完成能获取到高度之后，
            重新requestLayout刷新布局，然后再VISIBLE显示出来
             */
            setVisibility(View.INVISIBLE);
            post(()->{
                requestLayout();
                setVisibility(View.VISIBLE);
            });
        } else if (mMaxHeight >= 0 && measuredHeight >= mMaxHeight) {
            temHeightSpec = MeasureSpec.makeMeasureSpec(mMaxHeight, View.MeasureSpec.EXACTLY);
        }
        super.onMeasure(widthMeasureSpec, temHeightSpec);
    }
}